import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Test5 {
    /**
     * 目的:文件内容的扫描
     * @param args
     */
    public static void main(String[] args) throws IOException {
        //1.输入要扫描的文件目录
        System.out.println("请输入要扫描的文件目录路径");
        Scanner scanner = new Scanner(System.in);
        String source = scanner.next();
        File sourceFile = new File(source);
        if (!sourceFile.exists()){
            System.out.println("输入路径错误,文件不存在");
        }
        if (!sourceFile.isDirectory()){
            System.out.println("输入路径不是目录");
        }
        //2.输入扫描关键词
        System.out.println("请输入扫描关键词");
        String keyWord = scanner.next();
        //3.扫描文件
        List<File> list = new ArrayList<>();
        scanDirectory(sourceFile,keyWord,list);
        for (File s:list) {
            System.out.println(s);
        }
    }

    private static void scanDirectory(File sourceFile, String keyWord, List<File> list) throws IOException {
        File[] files = sourceFile.listFiles();
        if (files == null){
            return;
        }
        for (File s:files) {
            if (s.isDirectory()){
                scanDirectory(s,keyWord,list);
            }else {
                //4.扫描文件内容
                if (s.getName().contains(keyWord)){
                    list.add(s.getCanonicalFile());
                }
                if (scanFile(s,keyWord)){
                    list.add(s.getCanonicalFile());
                }
            }
        }
    }

    private static boolean scanFile(File s, String keyWord) {
        StringBuilder stringBuilder = new StringBuilder();
        try(InputStream inputStream = new FileInputStream(s)){
            Scanner scanner = new Scanner(s,"UTF-8");
            while (scanner.hasNextLine()){
                String str = scanner.nextLine();
                stringBuilder.append(str).append("\n");
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return stringBuilder.indexOf(keyWord) != -1;
    }
}
